package com.example.forum.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域请求过滤器
 * 解决前后端分离架构中的跨域问题
 */
@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 获取请求的来源
        String origin = request.getHeader("Origin");
        
        // 设置允许的来源，如果Origin头存在则使用其值，否则使用默认前端地址
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            // 开发环境下的前端地址，可根据实际情况调整
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        }
        
        // 允许的HTTP方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // 允许的HTTP头
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        // 是否允许发送Cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 预检请求的有效期，单位为秒
        response.setHeader("Access-Control-Max-Age", "3600");
        
        // 对于OPTIONS请求（预检请求），直接返回200状态码
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 对于非OPTIONS请求，继续执行后续过滤器链
            filterChain.doFilter(request, response);
        }
    }
} 